﻿using System;
using QQ2564874169.Core;
using QQ2564874169.Core.Lock;
using StackExchange.Redis;

namespace QQ2564874169.Core.Lock.Redis
{
    public class RedisLocker : ILocker
    {
        public static TimeSpan DefaultTimeout { get; set; }
        private IDatabase _db;
        private string _id;

        static RedisLocker()
        {
            DefaultTimeout = TimeSpan.FromSeconds(30);
        }

        public RedisLocker(IDatabase db)
        {
            _db = db;
            _id = Guid.NewGuid().ToString();
        }

        public bool IsLock(string key)
        {
            return _id.QQEquals(_db.LockQuery(key));
        }

        public bool Lock(string key)
        {
            return _db.LockTake(key, _id, DefaultTimeout);
        }

        public void UnLock(string key)
        {
            _db.LockRelease(key, _id);
        }
    }
}
